<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产品型号编码" prop="modelCode">
        <el-input
          v-model="queryParams.modelCode"
          placeholder="请输入产品型号编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['order:prodModel:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['order:prodModel:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['order:prodModel:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['order:prodModel:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ProdModelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品型号标识" align="center" prop="modelId" />
      <el-table-column label="产品型号编码" align="center" prop="modelCode" />
      <el-table-column label="型号说明" align="center" prop="description" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDataScope(scope.row)"
            v-hasPermi="['order:prodModel:edit']"
          >绑定</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['order:prodModel:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改生产产品型号对话框 -->
    <el-dialog :title="title" :visible.sync="openDataScope" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="型号编码" prop="modelCode">
          <el-input v-model="form.modelCode" placeholder="请输入产品型号编码" />
        </el-form-item>
        <el-form-item label="绑定站线">
          <el-checkbox v-model="stationExpand" @change="handleCheckedTreeExpand($event, 'station')">展开/折叠</el-checkbox>
          <el-checkbox v-model="stationNodeAll" @change="handleCheckedTreeNodeAll($event, 'station')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.stationCheckStrictly" @change="handleCheckedTreeConnect($event, 'station')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="stationOptions"
            show-checkbox
            default-expand-all
            ref="station"
            node-key="id"
            :check-strictly="!form.stationCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
        <el-form-item label="型号说明" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入型号说明" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProdModel, getProdModel, delProdModel, addProdModel, updateProdModel, stationTreeSelect } from "@/api/order/prodModel";

export default {
  name: "prodModel",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产产品型号表格数据
      ProdModelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      stationExpand: true,
      stationNodeAll: true,
      // 菜单列表
      menuOptions: [],
      // 站位列表
      stationOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        modelCode: null,
        description: null,
        creator: null,
        updater: null,
        deleted: null
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        modelCode: [
          { required: true, message: "请输入产品型号编码", trigger: "blur" },
          { min: 1, max: 30, message: "长度在 1 到 30 个字符", trigger: "blur" }
        ],
        description: [
          { required: true, message: "请输入型号说明", trigger: "blur" },
          { min: 1, max: 200, message: "长度在 1 到 200 个字符", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询生产产品型号列表 */
    getList() {
      this.loading = true;
      listProdModel(this.queryParams).then(response => {
        this.ProdModelList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.openDataScope = false;
      this.reset();
    },
    
    /** 分配数据权限操作 */
    handleDataScope(row) {
      this.reset();
      const stationTreeSelect = this.getStationTree(row.modelId);
      getProdModel(row.modelId).then(response => {
        this.form = response.data;
        this.openDataScope = true;
        this.$nextTick(() => {
          stationTreeSelect.then(res => {
            this.$refs.station.setCheckedKeys(res.checkedKeys);
          });
        });
      });
      this.title = "分配数据权限";
    },
    
    /** 根据角色ID查询部门树结构 */
    getStationTree(modelId) {
      return deptTreeSelect(modelId).then(response => {
        this.stationOptions = response.stations;
        return response;
      });
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.stationExpand = true,
      this.stationNodeAll = false,
      this.form = {
        modelId: null,
        modelCode: null,
        description: null,
        creator: null,
        createTime: null,
        updater: null,
        menuCheckStrictly: true,
        stationCheckStrictly: false,
        updateTime: null,
        deleted: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type == 'station') {
        let treeList = this.stationOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.station.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menu') {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
      } else if (type == 'station') {
        this.$refs.station.setCheckedNodes(value ? this.stationOptions: []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form.menuCheckStrictly = value ? true: false;
      } else if (type == 'station') {
        this.form.stationCheckStrictly = value ? true: false;
      }
    },

    /** 分配站位操作 */
    handleStationScope(row) {
      this.reset();
      const stationTreeSelect = this.getStationTree(row.modelId);
      getRole(row.roleId).then(response => {
        this.form = response.data;
        this.openDataScope = true;
        this.$nextTick(() => {
          stationTreeSelect.then(res => {
            this.$refs.station.setCheckedKeys(res.checkedKeys);
          });
        });
      });
      this.title = "分配数据权限";
    },
    
    /** 根据产品型号ID查询站位树结构 */
    getStationTree(modelId) {
      return stationTreeSelect(modelId).then(response => {
        this.stationOptions = response.stations;
        return response;
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.modelId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加生产产品型号";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const modelId = row.modelId || this.ids
      getProdModel(modelId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改生产产品型号";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.modelId != null) {
            updateProdModel(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProdModel(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const modelIds = row.modelId || this.ids;
      this.$modal.confirm('是否确认删除生产产品型号编号为"' + modelIds + '"的数据项？').then(function() {
        return delProdModel(modelIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('order/prodModel/export', {
        ...this.queryParams
      }, `prodModel_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
